package com.maker.controller;


import com.maker.entity.R;
import com.maker.entity.RefundInfo;
import com.maker.enums.OrderStatus;
import com.maker.service.AlipayDevelopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/api/ali-pay")
@Api(tags = "网站支付宝支付")
@Slf4j
public class AlipayController {
    private static final String CHARSET = "UTF-8";

    @Resource
    private AlipayDevelopService alipayDevelopService;

    @ApiOperation("统一收单下单并支付接口的调用")
    @PostMapping("/trade/page/pay/{productId}")
    public R tradePagePay(@PathVariable Long productId, HttpServletResponse httpResponse){


        log.info("统一收单下单并支付接口的调用");

        try {
            String  form = alipayDevelopService.trateCreate(productId);
            return new R("SUCCESS","支付页面已生成", form);
        } catch (Exception e) {
            e.printStackTrace();
            return new R("FAIL", "支付失败：" + e.getMessage(), null);
        }

    }
    @ApiOperation("支付通知")
    @PostMapping("/trade/notify")
    public String tradeNotify(@RequestParam Map<String,String> params){

        log.info("支付通知正在执行");
        log.info("支付宝通知返回参数：{}",params);
        String result = alipayDevelopService.rsaCheckV1(params);

        return result;

    }
    @ApiOperation("取消订单")
    @PostMapping("/trade/close/{orderNo}")
    public R cancelOrder(@PathVariable String orderNo){

        log.info("取消订单");
        alipayDevelopService.cancelOrder(orderNo);
        return new R("SUCCESS","订单取消成功！", "");
    }

    @ApiOperation("查询订单")
    @PostMapping("/trade/query/{orderNo}")
    public R queryOrder(@PathVariable String orderNo){

        log.info("查询订单");
       String result = alipayDevelopService.queryOrder(orderNo);
        return new R("SUCCESS","订单查询成功！", result);
    }

    @ApiOperation("申请退款")
    @PostMapping("/trade/refund/{orderNo}/{reason}")
    public R refunds(@PathVariable String orderNo,@PathVariable String reason){

        log.info("申请退款");
        RefundInfo refundInfo= alipayDevelopService.refund(orderNo,reason);
        //根据自身业务去优化
        if(refundInfo.equals(OrderStatus.REFUND_SUCCESS.getType())){
            return new R("SUCCESS","退款成功！", refundInfo.getRefundStatus());
        }else{
            return new R("FAIL","退款失败！", refundInfo.getRefundStatus());
        }
    }

    @ApiOperation("获取账单url")
    @PostMapping("/bill/download/query/{billdate}/{type}")
    public R queryTradeBill(@PathVariable String billdate,@PathVariable String type){

        log.info("获取账单url");
        String downloadurl = alipayDevelopService.queryTradeBill(billdate,type);
        //根据自身业务去优化
        return new R("SUCCESS","成功！", downloadurl);
    }




}
